<template>
  <div>
    <!-- echarts -->
    <div class="myChart" ref="chartRef"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    chartData: Object,
  },
  methods: {
    //画折线图
    renderLine(obj) {
      //默认值
      let defaultOptions = {
        title: "金额图表",
      };
      //最终参数 传入参数合并默认值
      let finalObj = { ...defaultOptions, ...obj };
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(this.$refs.chartRef);
      //配置项
      let options = {
        //图表标题
        title: {
          text: finalObj.title,
          left: 15,
          top: 15,
        },
        //工具提示
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        //图例组件展现了不同系列的标记(symbol)，颜色和名字。
        legend: {
          top: 15,
        },
        //工具箱
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },

        //网格
        grid: {
          left: "5%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: finalObj.xData.map(function (str) {
              return str.replace(" ", "\n");
            }),
          },
        ],
        yAxis: [
          {
            type: "value",
            max:'300',
          },
        ],
        //核心数据
        series: finalObj.series,
      };
      // 绘制图表
      myChart.setOption(options);
    },
  },

  //方式2 监听数据变化才渲染
  watch: {
    chartData() {
      this.renderLine(this.chartData);
    },
  },
  mounted() {
    //思路一
    // this.renderLine(this.chartData);
  },
};
</script>

<style lang="scss" scoped>
.myChart {
  height: 300px;
  background: white;
}
</style>